<template>
	<basic-container>
		<avue-form ref="obj" v-model="groupData" :option="optionView"  style="padding-top: 15px;">
			<template slot="menuForm">
				<el-button type="primary" size="mini" @click="handleSubmit('obj')">确定</el-button>
				<el-button size="mini" @click="handlecancle()">取 消</el-button>
			</template>

			<!-- 广告类型 -->
			<template slot="adType">
				<div>
					<el-select v-model="groupData.adTypeName" placeholder="请选择广告类型" @change="getAdType">
						<el-option v-for="item in typeData" :key="item.label" :lable="item.lable" :value="item.value">
							<span style="float: left">{{ item.label }}</span>
						</el-option>
					</el-select>
				</div>
			</template>
			<!-- 广告类型id -->
			<template slot="adTypeValue">
				<div>
					<!--<el-col style="position: absolute;left: -100px;width: 100px;">-->
						<!--<div style="text-align: right;font-size: 14px;color: #606266;">{{idTitle}}</div>-->
					<!--</el-col>-->
					<!--<el-col style="width: 100%;" v-if="idTitle!=''">-->
						<!--<el-input v-model="groupData.adTypeValue"></el-input>-->
					<!--</el-col>-->
					<el-select v-show="groupData.adType == 1" placeholder="请输入关键词"
								filterable
								remote
								:remote-method="getSelectList" v-model="value" popper-class="selectJob" size="mini">
						<el-option v-for="item in restoreTable" :key="item.id" :label="item.goodsName" :value="item.id">
							<span style="float: left;width:120px" :title="item.goodsName">{{ item.goodsName }}</span>
						</el-option>
						<div style="text-align:center">
							<span class="text" v-show="selectPage!=1" @click.stop="prevePage" >上一页</span>
							<span class="text" style="padding-left: 30px; " @click.stop="nextPage" v-show="selectPage !=pageCount">
							下一页
						</span>
						</div>
					</el-select>
					<el-select v-show="groupData.adType == 2"  placeholder="请输入关键词"
							   filterable
							   remote
							   :remote-method="getSelectList" v-model="value" popper-class="selectJob" size="mini">
						<el-option v-for="item in restoreTable" :key="item.id" :label="item.storeName" :value="item.id">
							<span style="float: left;width:120px" :title="item.storeName">{{ item.storeName }}</span>
						</el-option>
					</el-select>
					<el-select v-show="groupData.adType == 4 || groupData.adType == 6 || groupData.adType == 8" placeholder="请输入关键词"
							   filterable
							   remote
							   :remote-method="getSelectList" v-model="value" popper-class="selectJob" size="mini">
						<el-option v-for="item in restoreTable" :key="item.id" :label="item.acTitle" :value="item.id">
							<span style="float: left;width:120px" :title="item.acTitle">{{ item.acTitle }}</span>
						</el-option>
						<div style="text-align:center">
							<span class="text" v-show="selectPage!=1" @click.stop="prevePage">上一页</span>
							<span class="text" style="padding-left: 30px;" @click.stop="nextPage" v-show="selectPage !=pageCount">
								下一页
							</span>
						</div>
					</el-select>
				</div>
			</template>
			<!--竞价-->
			<template slot="adPrice">
				<div>
					<el-tooltip class="item" effect="dark" content="竞价相同时，先出价的排在前面" placement="top-start">
						<el-input v-model="groupData.adPrice" @change="changeAdPrice"></el-input>
					</el-tooltip>
					<!--<el-input v-model.number="groupData.adPrice"
                    @change="changeAdPrice"
          ></el-input>-->
				</div>
			</template>
			<!--账户余额-->
			<template slot="adAmount" style="width: 100%;position: relative;">
				<div>
					<el-col style="width: calc(100% - 85px);">
						<div style="font-size: 16px;color: #007AFF;">{{groupData.adAmount}}</div>
						<!-- <el-input type="text" v-model.number="groupData.adAmount"></el-input> -->
					</el-col>
					<el-col style="width: 70px;margin-left: 15px;">
						<el-button type="primary" @click="gotoRecharge">充值</el-button>
					</el-col>
				</div>
			</template>
			<!-- 开始时间 -->
			<template slot="adBeginTime" style="width: 100%;position: relative;">
				<div>
					<el-date-picker format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" v-model="groupData.adBeginTime"
						type="datetime" placeholder="选择开始时间" @change="getAddTime">
					</el-date-picker>
				</div>
			</template>
			<!-- 结束时间 -->
			<template slot="adEndTime" style="width: 100%;position: relative;">
				<div>
					<el-date-picker format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" v-model="groupData.adEndTime" type="datetime"
						placeholder="选择结束时间" @change="getAddTime">
					</el-date-picker>
				</div>
			</template>
			<!-- 广告位 -->
			<template slot="adApId" style="width: 100%;position: relative;">
				<div>
					<el-col style="width: calc(100% - 105px);">
						<el-select v-model="groupData.adApId" placeholder="请选择所属广告位" @change="getPosData">
							<el-option v-for="item in posData" :key="item.value" :label="item.label" :value="item.value">
							</el-option>
						</el-select>
					</el-col>
					<el-col style="width: 90px;margin-left: 15px;">
						<el-button icon="el-icon-search" type="primary" @click="look">查询</el-button>
					</el-col>
				</div>
			</template>
			<!-- 选择广告图片 -->
			<template slot="adAccUrl">
				<div style="width: 100%;position: relative;">
					<el-col style="width: calc(100% - 158px);">
						<el-input v-model="groupData.adAccUrl" @focus="$refs.selFile.open()" readonly  :placeholder="placeholder"></el-input>
					</el-col>
					<el-col style="width: 38px;height: 38px;overflow: hidden;margin-left: 15px;background: #f5f6f7;text-align: center;">
						<el-image :src="groupData.adAccUrl" width="38" height="38">
							<div slot="error" class="image-slot">
								<i class="el-icon-picture-outline"></i>
							</div>
						</el-image>
					</el-col>
					<el-col style="width: 90px;margin-left: 15px;">
						<el-button icon="el-icon-search" type="primary" @click="$refs.selFile.open()">预览</el-button>
						<selFile ref="selFile" @callback="selFileCallBack" albumCode="store" dialogTitle="选择图片" selectType="radio"
							selMaxWidth="300px" selMaxHeight="300px"></selFile>
					</el-col>
					<div style="clear: both;"></div>
					<div class="previewAdvBox" v-if="isView">
						<div class="biddingPrice">
							<p class="biddingPrice-title">竞价排行
								<!--<span @click="viewRules">查看规则</span>-->
								<el-popover placement="bottom" title="竞价规则" width="400" trigger="click">
									<div style="font-size: 13px;color: #999;line-height: 24px;">
										<p style="color: #007DDB;">竞价购买：</p>购买时账户余额最少需要能扣费十次,根据购买广告的金额进行排名，不同的排名有不同概率的展示机会;
										<p style="color: #007DDB;">收费：</p><span style="color: #333;">价格：</span>取下一名竞价广告的竞价，最后一名取自身竞价</br>
										<span style="color: #333;">计费方式：</span>每个ip点击扣费一次（十分钟内重复点击算一次）
										<p style="color: #007DDB;">展示：</p>根据实时的排行按照对应的概率实时刷新广告
										<p style="color: #007DDB;">下架广告：</p><span style="color: #333;">1、</span>随时手动下架广告</br>
										<span style="color: #333;">2、</span>剩余广告币不足下架</br>
										<span style="color: #333;">3、</span>有新的广告参与竞价更高，自身广告跌出了展示排行
									</div>
									<el-button slot="reference" type="text" size="mini">查看规则</el-button>
								</el-popover>
							</p>
							<div class="biddingPrice-list">
								<!--<avue-data-progress :option="optionPrice" v-for="item in tableData" :key="item.id">-->
								<avue-data-progress :option="optionPrice">
								</avue-data-progress>
							</div>
						</div>
						<div class="previewAdv">
							<div class="previewBox swperBanner">
								<el-image :src="previewImgUrl" style="width: 375px;height:188px;">
									<div slot="error" class="image-slot">
										<i class="el-icon-picture-outline"></i>
									</div>
								</el-image>
							</div>
						</div>
					</div>
				</div>
			</template>
		</avue-form>

	</basic-container>
</template>

<script>
	import selFile from "@/components/file/selFile";
	import uploadPic from "@/components/file/uploadPic";
	import {
    		isInteger,
			testAccountName
    	} from '@/util/util';
	import {
		add,
		getPosList,
		getlistPoster,
		getDetail,
		getAmount
	} from "@/api/base/store/seller/buyAdvert";
	import {
		mapGetters
	} from "vuex";
    import {
        getStoreDetail,
        getGoodsList,
        getActList
    } from "@/api/base/store/seller/advert";
	export default {
		data() {
			return {
                value:'',
                total: null, // 获取总数据量
                pageCount: null, // 获取总页数
                selectPage: 1, // 当前页数
                restoreTable: [], //当前页数数据
                selectQuery:"",
				isView: false,
				avueformRules: {},
				optionView: { //表单组配置
					// card: true,
					mock: false,
					submitBtn: false,
					emptyBtn: false,
					menuPostion: 'right',
					labelWidth: '120',
					column: [
						{
							label: "广告位",
							prop: "adApId",
							type: "select",
							formslot: true,
							tip: '请选择广告位',
							tipPlacement: 'bottom',
							span: 12,
							rules: [{
								required: true,
								message: "必须选择广告位",
								trigger: 'change'
							}, ],
						},
						{
							label: "广告名称",
							prop: "adTitle",
							formslot: false,
							tip: '输入广告名称',
							tipPlacement: 'bottom',
							span: 12,
							rules: [{
								required: true,
								validator: testAccountName,
								trigger: 'blur'
							}, ],
						},
						{
							label: "广告类型",
							prop: "adType",
							type: "select",
							formslot: true,
							span: 12,
						},
						{
						    label:"广告类型值选择",
							prop: "adTypeValue",
							//display: false,
							formslot: true,
							span: 12,
						},
						{
							label: "竞价",
							prop: "adPrice",
							formslot: true,
							span: 12,
							rules: [{
								required: true,
								message: "必须填写竞价",
								trigger: 'blur'
							},
                            {
                                validator: isInteger,
                                trigger: 'blur'
                            }],
						},
						{
							label: "账户余额",
							prop: "adAmount",
							formslot: true,
							span: 12,
						},
						{
							label: "开始时间",
							prop: "adBeginTime",
							formslot: true,
							span: 12,
							rules: [{
								required: true,
								message: "必须填写开始时间",
								trigger: 'blur'
							}, ],
						},
						{
							label: "结束时间",
							prop: "adEndTime",
							formslot: true,
							span: 12,
							rules: [{
								required: true,
								message: "必须填写结束时间",
								trigger: 'blur'
							}, ],
						},
						{
							label: "广告图片",
							prop: "adAccUrl",
							formslot: true,
							span: 24,
							rules: [{
								required: true,
								message: "必须选择广告图片",
								trigger: 'blur'
							},{
								min:0,
								trigger:'change'
							} ],
						},
					]
				},
				groupData: {
					adTitle: "",
					adApId: "",
					adType: "",
					adAmount: '',
					adTypeName: '',
					adTypeValue: "",
					adBeginTime: "",
					adEndTime: "",
					adAccUrl: "",
					mark: ""
				},
				optionPrice: {
					span: 24,
					data: []
				},
				load: false,
				placeholder:'',
				previewImgUrl:'',
				apPrice: '',
				tableData: [],
				idTitle: '',
				form: {},
				query: {},
				loading: true,
				box: false,
				data: [],
				dicData: [],
				posData: [],
				typeData: [],
				advertFlag:true,
			};
		},
		watch: {
			// 'groupData.adType'() {
			// 	if (this.groupData.adType != '') {
			// 		this.optionView.column[3].display = true
			// 	}
			// },
			// 'groupData.adApId'() {
			// 	if (this.groupData.adType != '') {
			// 		this.optionView.column[3].display = true
			// 	}
			// },
            'groupData.adType'(){
				//重置
				this.total= null; // 获取总数据量
				this.pageCount= null; // 获取总页数
				this.selectPage=1; // 当前页数
				this.restoreTable=[]; //当前页数数据
				this.selectQuery="";
                if(this.dialogVisible!=false){
                    this.getSelectList();
                }

            }
		},
		created() {
			this.getAmount();
			// 下拉广告位
			getPosList(1, 1, false).then(res => {
				const data = res.data;
				this.posData = data.data
			})
			this.dicData = JSON.parse(localStorage.getItem("mall-dictionary")).content;
			this.typeData = this.dicData.ADVERT_TYPE
		},
		components: {
			selFile,
			uploadPic
		},
		computed: {
			...mapGetters(["permission", 'userInfo', 'dictionariy']),
			permissionList() {
				return {

				};
			},
		},
		methods: {
            getSelectList (query) {
                //商品选择框
                //查询参数
                let param={goodsName:query,goodsStatus:0};
                this.selectQuery = query;
                this.value="";
                let getListMethod=getGoodsList;
                //1商品详情  2店铺  4促销活动 6秒杀活动 8拼团
                if(this.groupData.adType==2){
                    getStoreDetail().then(res => {
                        let store = res.data.data;
                        let storeSelect={
                            storeName:store.storeName,
                            id:store.id
                        };
                        this.restoreTable=[];
                        this.restoreTable.push(storeSelect);
                        this.total = res.data.count; // 数据总数量
                        this.pageCount = Math.ceil(this.total / 10); // 因为我每次只请求10条， 所以算出总页数
                        this.value = this.restoreTable[0].id; //店铺只有一个，所以选取第一条数据;
                    });
                    return ;
                }else if(this.groupData.adType==4){
                    getListMethod=getActList;
                    param={id:this.value,isPromotion:true};
                }else if(this.groupData.adType==6){
                    getListMethod=getActList;
                    param={id:this.value,acType:3};
                }else if(this.groupData.adType==8){
                    getListMethod=getActList;
                    param={id:this.value,acType:2};
                }
                getListMethod(this.selectPage,10,param).then(res => {
                    this.restoreTable = res.data.data;
                    this.total = res.data.count; // 数据总数量
                    this.pageCount = Math.ceil(this.total / 10); // 因为我每次只请求20条， 所以算出总页数
                });
            },
            prevePage () {
                if (this.selectPage > 1) { // 判断点击的页数是否小于1
                    --this.selectPage ;
                };
                this.getSelectList(this.selectQuery);
            },
            nextPage () {
                if (this.selectPage < this.pageCount) { // 判断点击的页数是否小于总页数;
                    ++this.selectPage;
                    this.getSelectList(this.selectQuery);
                }
            },
			// 选择图片
			selFileCallBack(obj) {
				this.groupData.adAccUrl = obj[0];
				console.log(this.groupData.adAccUrl)
			},
			changeAdPrice(val) {
				if (!this.apPrice) {
					this.$message({
						type: "error",
						message: "请选择广告位"
					});
				} else {
					if (this.apPrice > val) {
						this.$message({
							type: "error",
							message: "竞价不能低于广告位的价格"+this.apPrice
						})
						this.groupData.adPrice = '';
					}
				}
			},
			//点击充值跳转账户资金页面
			gotoRecharge() {
				this.$router.replace('/account/seller/userAccount')
			},
			//点击竞价查询
			look() {
				if (!this.groupData.adApId) {
					this.$message({
						type: "error",
						message: "请选择广告位!"
					});
				} else {
					this.isView = true;
					let orderBy = 0;
					let adApId = this.groupData.adApId
					getlistPoster(orderBy, adApId).then(res => {
						if (res.status == 200) {
							this.tableData = res.data.data.listMap
							console.log(this.tableData)
							this.optionPrice.data = this.tableData.map(prop => {
								return {
									title: `竞价：${prop.adPrice}(${prop.storeName})`,
									color: 'rgb(56, 161, 242)',
									count: prop.probability
								}
							})
						}
					})
				}

			},
			getAddTime() {

				if (this.groupData.adEndTime !="" && this.groupData.adBeginTime > this.groupData.adEndTime) {
					this.$message({
						type: "error",
						message: "结束时间不能小于开始时间"
					});
					this.groupData.adEndTime = ''
				}
			},
			checkStartTime() {
				if (this.groupData.adEndTime != null && this.groupData.adEndTime != undefined && this.groupData.adEndTime != "") {
					if (this.groupData.adBeginTime > this.groupData.adEndTime) {
						this.$message({
							type: "error",
							message: "开始时间不能大于结束时间"
						});
						this.groupData.adBeginTime = '';
						return;
					}
				}
				if (this.groupData.adBeginTime < new Date().getTime()) {
					this.$message({
						type: "error",
						message: "开始时间不能小于当前时间"
					});
					this.groupData.adBeginTime = ''
				}
			},
			//选择广告类型
			getAdType(val) {
				for (let obj of this.typeData) {
					if (obj.value == val) {
						this.groupData.adTypeName = obj.label
						this.groupData.adType = obj.value
						if (obj.value == 1) {
							this.idTitle = '商品id：'
						} else if (obj.value == 2) {
							this.idTitle = '店铺id：'
						} else if (obj.value == 4) {
							this.idTitle = '促销活动id：'
						} else if (obj.value == 6) {
							this.idTitle = '秒杀活动id：'
						} else if (obj.value == 8) {
							this.idTitle = '拼团活动id：'
						} else if (obj.value == 7) {
							this.idTitle = '聚合页id：'
						}
					}
				}

			},
			getPosData(val) {
				//选择的竞价
				getDetail(val).then(res => {
					if (res.status == 200) {
						this.apPrice = res.data.data.apPrice
						let  apWidth=res.data.data.apWidth
						let  apHeight=res.data.data.apHeight
						this.placeholder = '最佳尺寸 ： ' + apWidth+'像素 x '+apHeight+'像素'
						this.previewImgUrl = res.data.data.previewImgUrl
						if (res.data.data.mark == 1) {
							this.mark = '1'
						} else {
							this.mark = '2'
						}
					}
				})
			},
			handleSubmit(obj) {
				if (this.advertFlag) {
					this.advertFlag = false;
				} else {
					return false;
				}
			    this.groupData.adTypeValue=this.value;
				this.load = true
				this.$refs[obj].validate((valid) => {
					if (valid) {
						if(this.groupData.adType && !this.groupData.adTypeValue){
							this.$message.error("请选择" + this.idTitle);
							this.load = false;
							this.advertFlag = true;
							return;
						}
						if(this.groupData.adAmount < this.groupData.adPrice * 10){
							this.$message.error("账户金额不够");
							this.load = false;
							this.advertFlag = true;
							return;
						}
						if (!this.groupData.adAccUrl) {
							this.$message({
								type: "error",
								message: "请选择广告图片!"
							});
							this.load = false;
							this.advertFlag = true;
							return;
						}
						if (!this.groupData.adPrice) {
							this.$message({
								type: "error",
								message: "请输入竞价!"
							});
							this.load = false;
							this.advertFlag = true;
						} else {
							this.groupData.mark = this.mark
							add(this.groupData).then((res) => {
								if (res.status == 200) {
									this.load = false
									this.advertFlag = true
									this.$message({
										type: "success",
										message: "购买广告成功!"
									});
									//跳转到已购买广告页面
									this.$router.replace('/base/advert/seller/advert');
									// this.$router.go(0)
								}
								setTimeout(() => {
									this.advertFlag = true;
								}, 1000);
							})
						}
					} else {
						this.$message({
							type: "error",
							message: "请输入广告的必要信息!"
						});
						this.load = false;
						this.advertFlag = true
						return false;
					}
				});
			},
			handlecancle() {
				this.$refs.obj.resetForm();
				this.getAmount()
				this.isView=false
			},
			getAmount() {
				getAmount().then(res => {
					this.groupData.adAmount = res.data.data.adAmount
				});
			},
		}
	};
</script>

<style scoped lang="scss">
	.previewAdvBox {
		width: 100%;
		display: flex;
		flex-wrap: nowrap;
		justify-content: space-between;
		align-items: center;
	}

	.biddingPrice {
		width: calc(100% - 540px);
	}

	.biddingPrice-list {
		height: 630px;
		overflow: auto;
	}

	.biddingPrice-title {
		height: 80px;
		line-height: 100px;
		font-size: 16px;
		border-bottom: 1px dashed #e5e5e5;
		margin-bottom: 20px;

		span {
			padding: 20px;
			color: #F39800;
			font-size: 14px;
			text-decoration: underline;
		}
	}
	.text {
		cursor:pointer;
	}

	.previewAdv {
		border: 1px solid #e5e5e5;
		background: #fff;
		width: 375px;
		height: 667px;
	}

	.previewBox {
		width: 100%;
		height: 188px;
		background: #f5f7fa;
		font-size: 30px;
		text-align: center;
		line-height: 188px;
	}

	.previewBox.active {
		border: 1px solid red;
	}

	.image-slot {
		width: 40px;
		height: 40px;
		background: #f5f6f7;
		text-align: center;
	}
</style>
